import {defineStore} from 'pinia'
import {ref} from 'vue'
import {
    apiBatchSaveArticles,
    apiSaveArticle,
    apiTranslateArticle,
    batchDeleteArticles,
    deleteArticleApi,
    getArticleList,
    importArticles,
    updateArticleStatus,
    translateArticle,
    translateText,
    getArticleTranslations
} from '@/api/article'
import {ElMessage} from 'element-plus'

export const useArticleStore = defineStore('article', () => {
    const articles = ref([])
    const total = ref(0)
    const loading = ref(false)
    const translations = ref({})

    // 获取文章列表
    const fetchArticles = async (query) => {
        try {
            loading.value = true
            const { data } = await getArticleList(query)
            articles.value = data.records
            total.value = data.total
        } catch (error) {
            ElMessage.error(error.message || '获取文章列表失败')
        } finally {
            loading.value = false
        }
    }

    // 导入文章
    const importArticleData = async (formData) => {
        try {
            loading.value = true
            const { data } = await importArticles(formData)
            ElMessage.success(`成功导入${data.total}篇文章`)
            return data
        } catch (error) {
            ElMessage.error(error.message || '导入文章失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 更新文章状态
    const updateStatus = async (id, status) => {
        try {
            await updateArticleStatus(id, status)
            ElMessage.success('更新状态成功')
        } catch (error) {
            ElMessage.error(error.message || '更新状态失败')
            throw error
        }
    }

    // 删除单个文章
    const deleteArticle = async (id) => {
        try {
            await deleteArticleApi(id)
            ElMessage.success('删除成功')
        } catch (error) {
            ElMessage.error(error.message || '删除失败')
            throw error
        }
    }

    // 批量删除文章
    const batchDelete = async (ids) => {
        try {
            await batchDeleteArticles(ids)
            ElMessage.success('批量删除成功')
        } catch (error) {
            ElMessage.error(error.message || '批量删除失败')
            throw error
        }
    }

    // 保存文章
    const saveArticle = async (data) => {
        try {
            await apiSaveArticle(data)
        } catch (error) {
            ElMessage.error(error.message || '保存失败')
            throw error
        }
    }

    // 批量翻译并保存文章
    const batchTranslateArticles = async (data) => {
        try {
            return await apiTranslateArticle(data)
        } catch (error) {
            ElMessage.error(error.message || '批量翻译失败')
            throw error
        }
    }

    // 翻译并保存单篇文章 - FIX: Uncomment and implement properly
    const singleTranslateArticles = async (data) => {
        try {
            // Convert the nested translations object to the format expected by the backend
            const apiData = {
                id: data.id,
                targetLanguage: Object.keys(data.translations)[0]
            }

            return await translateArticle(apiData)
        } catch (error) {
            ElMessage.error(error.message || '翻译文章失败')
            throw error
        }
    }

    // 翻译并保存文本
    const singleTranslateText = async (data) => {
        try {
            return await translateText(data)
        } catch (error) {
            ElMessage.error(error.message || '翻译文本失败')
            throw error
        }
    }

    const fetchArticleTranslations = async (articleId) => {
        try {
            const { data } = await getArticleTranslations(articleId)

            // Initialize the translations object for this article if it doesn't exist
            if (!translations.value[articleId]) {
                translations.value[articleId] = {}
            }

            // Process and store the translations
            if (data && data.length > 0) {
                data.forEach(translation => {
                    translations.value[articleId][translation.language] = {
                        title: translation.title,
                        description: translation.description
                    }
                })
            }

            return data
        } catch (error) {
            ElMessage.error(`获取文章翻译失败: ${error.message || '未知错误'}`)
            throw error
        }
    }

    const hasTranslation = (articleId, language) => {
        return translations.value[articleId] &&
            translations.value[articleId][language] !== undefined
    }

    const batchSaveArticles = async (articles) => {
        try {
            return await apiBatchSaveArticles({articles})
        } catch (error) {
            ElMessage.error(error.message || '批量保存失败')
            throw error
        }
    }

    return {
        articles,
        total,
        loading,
        translations,
        fetchArticles,
        importArticleData,
        updateStatus,
        deleteArticle,
        batchDelete,
        saveArticle,
        batchTranslateArticles,
        batchSaveArticles,
        singleTranslateArticles,
        singleTranslateText,
        fetchArticleTranslations,
        hasTranslation
    }
})